import React, { useEffect, useState, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { selectVideoFilterById, updateVideoProperties } from '@/store/videosSlice';
import { selectStickerById, updateStickerProperties } from '@/store/stickersSlice';
import type { RootState } from '@/store';
import { Form, Select, Spin, Typography, InputNumber, Row, Col, Button } from 'antd';
import { createGlobalStyle } from 'styled-components';
import { getAllFilters } from '@/services/project';

const { Title, Text } = Typography;
const { Option } = Select;

interface ConfigVideoFilterFormProps {
    videoId: string;
}

// 全局 Ant Design 深色主题样式
const GlobalAntdDarkThemeStyle = createGlobalStyle`
    /* 自定义滚动条样式 */
    .config-video-filter-scroll::-webkit-scrollbar {
        width: 3px; background: transparent;
    }
    .config-video-filter-scroll::-webkit-scrollbar-thumb {
        background: #715BB8; border-radius: 4px;
    }
    /* 表单标签 */
    .ant-form-item-label > label {
        color: #FFFFFF !important;
    }
    /* 输入/选择控件 */
    .ant-input, .ant-input-number, .ant-select-selector {
        background-color: #3C3C3C !important;
        color: #FFFFFF !important;
        border-color: #555555 !important;
    }
    .ant-input:hover, .ant-input:focus,
    .ant-input-number:hover, .ant-input-number:focus,
    .ant-select:not(.ant-select-disabled):hover .ant-select-selector {
        border-color: #888888 !important;
        box-shadow: 0 0 0 2px rgba(136, 136, 136, 0.2) !important;
    }
    .ant-input-number-handler-wrap { background-color: #3C3C3C !important; }
    .ant-input-number-handler { color: #FFFFFF !important; border-color: #555555 !important; }
    .ant-select-dropdown { background-color: #3C3C3C !important; }
    .ant-select-item-option { color: #FFFFFF !important; }
    .ant-select-item-option-selected { background-color: #555555 !important; }
    .ant-select-arrow { color: #FFFFFF !important; }
`;

const ConfigVideoFilterForm: React.FC<ConfigVideoFilterFormProps> = ({ videoId }) => {
    const dispatch = useDispatch();
    const [form] = Form.useForm();

    // 判断是否为贴纸
    const isSticker = videoId?.includes('sticker') || false;

    // 根据是否为贴纸选择不同的selector
    const mediaFilter = useSelector((state: RootState) => {
        if (!videoId) return null;
        if (isSticker) {
            const sticker = selectStickerById(state, videoId);
            return sticker?.filter || null;
        }
        return selectVideoFilterById(state, videoId);
    });

    const [filtersData, setFiltersData] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        setLoading(true);
        getAllFilters()
            .then((res) => {
                const allFilters = [...(res.data?.data?.free || []), ...(res.data?.data?.vip || [])];
                setFiltersData(allFilters);
            })
            .catch((error) => console.error('获取滤镜数据失败:', error))
            .finally(() => setLoading(false));
    }, []);

    useEffect(() => {
        if (mediaFilter) {
            form.setFieldsValue({
                filter_type: mediaFilter.filter_type,
                intensity: mediaFilter.intensity,
            });
        } else {
            form.resetFields(['filter_type', 'intensity']);
        }
    }, [mediaFilter, form]);

    // 专门处理滤镜选择变化的方法
    const handleFilterChange = useCallback(
        (filterType: string) => {
            if (!videoId) return;

            if (!filterType) {
                // 如果滤镜类型被清空，则移除整个滤镜对象
                if (isSticker) {
                    dispatch(
                        updateStickerProperties({
                            id: videoId,
                            updates: { filter: undefined },
                        })
                    );
                } else {
                    dispatch(
                        updateVideoProperties({
                            id: videoId,
                            updates: { filter: undefined },
                        })
                    );
                }
            } else {
                // 获取当前强度值
                const intensity = form.getFieldValue('intensity') ?? 100.0;
                const filterData = {
                    filter_type: filterType,
                    intensity: intensity,
                };

                if (isSticker) {
                    dispatch(
                        updateStickerProperties({
                            id: videoId,
                            updates: { filter: filterData },
                        })
                    );
                } else {
                    dispatch(
                        updateVideoProperties({
                            id: videoId,
                            updates: { filter: filterData },
                        })
                    );
                }
            }
        },
        [videoId, dispatch, form, isSticker]
    );

    // 专门处理强度变化的方法
    const handleIntensityChange = useCallback(
        (intensity: number) => {
            if (!videoId) return;

            const filterType = form.getFieldValue('filter_type');
            if (filterType) {
                const filterData = {
                    filter_type: filterType,
                    intensity: intensity ?? 100.0,
                };

                if (isSticker) {
                    dispatch(
                        updateStickerProperties({
                            id: videoId,
                            updates: { filter: filterData },
                        })
                    );
                } else {
                    dispatch(
                        updateVideoProperties({
                            id: videoId,
                            updates: { filter: filterData },
                        })
                    );
                }
            }
        },
        [videoId, dispatch, form, isSticker]
    );

    if (!videoId) {
        return (
            <div
                style={{
                    padding: '20px',
                    color: '#FFFFFF',
                    backgroundColor: '#282828',
                    height: '100%',
                }}
            >
                未选择任何视频片段
            </div>
        );
    }

    return (
        <>
            <GlobalAntdDarkThemeStyle />
            {/* **改动1: 主容器样式与之前表单对齐** */}
            <div
                className="config-video-filter-scroll"
                style={{
                    maxHeight: 540,
                    overflowX: 'hidden',
                    overflowY: 'auto',
                    backgroundColor: '#282828',
                    color: '#FFFFFF',
                    padding: '16px',
                    borderRadius: '8px',
                }}
            >
                <Title level={4} style={{ marginBottom: 16, color: '#FFFFFF' }}>
                    属性面板
                </Title>
                <Title level={5} style={{ marginTop: 0, marginBottom: 8, color: '#FFFFFF' }}>
                    当前滤镜
                </Title>
                {/* **改动2: 优化当前滤镜显示** */}
                <div
                    style={{
                        backgroundColor: '#3C3C3C',
                        color: '#FFFFFF',
                        padding: '8px 12px',
                        borderRadius: '4px',
                        marginBottom: '24px',
                        border: '1px solid #555555',
                    }}
                >
                    <Text style={{ color: '#FFFFFF' }}>{mediaFilter ? `效果: ${mediaFilter.filter_type}, 强度: ${mediaFilter.intensity}%` : '无滤镜'}</Text>
                </div>

                <Form form={form} layout="vertical" initialValues={{ intensity: 100.0 }}>
                    {/* 优化布局，将滤镜和强度并排显示 */}
                    <Row gutter={16} align="bottom">
                        <Col span={16}>
                            <Form.Item label="滤镜效果" name="filter_type">
                                <Spin spinning={loading}>
                                    <Select
                                        placeholder="请选择或清除滤镜"
                                        allowClear
                                        showSearch
                                        filterOption={(input, option) => String(option?.children).toLowerCase().includes(input.toLowerCase())}
                                        onChange={handleFilterChange}
                                    >
                                        {filtersData.map((filter) => (
                                            <Option key={filter.name} value={filter.name}>
                                                {filter.display_name}
                                                {filter.is_vip ? ' (VIP)' : ''}
                                            </Option>
                                        ))}
                                    </Select>
                                </Spin>
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="强度" name="intensity">
                                <InputNumber min={0} max={100} step={1} style={{ width: '94%' }} addonAfter="%" onChange={() => handleIntensityChange} />
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </div>
        </>
    );
};

export default ConfigVideoFilterForm;
